package com.hyopt.modules.app.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hyopt.common.push.Notification.UmAndriodNotification;
import com.hyopt.common.push.Notification.UmIOSNotification;
import com.hyopt.common.push.config.UmConfig;
import com.hyopt.common.push.util.UmPushUtil;
import com.hyopt.common.utils.Constant;
import com.hyopt.common.utils.DateUtils;
import com.hyopt.common.utils.R;
import com.hyopt.common.utils.SmsConstant;
import com.hyopt.modules.app.entity.UserEntity;
import com.hyopt.modules.app.form.AlarmListInfoVo;
import com.hyopt.modules.app.service.AlarmInfoService;
import com.hyopt.modules.app.service.SmsService;
import com.hyopt.modules.app.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author ：Li9527
 * @date ：Created in 2020-01-08 9:01
 * @description：${description}
 * @modified By：
 * @version: 1.0.0
 */
@RestController
@RequestMapping("/app/callback")
@Api(value = "AppCallBackController", tags = {"回调业务相关接口"})
@Slf4j
public class AppCallBackController {


    @Autowired
    private AlarmInfoService alarmInfoService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    /**
     * 获取联河光子推送过来的包体
     *
     * @return
     */
    @PostMapping("/info")
    @ApiOperation("获取联河光子推送过来的包体")
    public R List(HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        log.info(params.toString());

        //todo 数据解析
        String event=params.get("event");

        UmAndriodNotification andUm=null;
        UmIOSNotification iosUm=null;
        // todo 推送 44位 安卓 64位 ios
        if("alarm".equals(event)){
            // 报警 - 通知
            JSONObject json=new JSONObject();
            json.put("envent","newAlarm");
            String ids=params.get("id");//报警Id
            Map tokens=alarmInfoService.getUserTokenByAlarmId(ids);
            if(tokens.containsKey("and")){
                andUm=(UmAndriodNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.Android.name(),UmConfig.CasetType.listcast.name());
                andUm.setDisplayType(UmConfig.DisplayType.notification.name());
                andUm.setTitle("通知");
                andUm.setTicker("您有一条新的报警信息!");
                andUm.setText("您有一条新的报警信息!");
                andUm.setDeviceTokens(tokens.get("and").toString());
                andUm.setAfterOpenAction("go_app");
                andUm.setPlaySound(true);
                andUm.setPlayLights(true);
                andUm.setPlayVibrate(true);
                andUm.setDescription("您有一条新的报警信息");
            }
            if(tokens.containsKey("ios")){
                iosUm=(UmIOSNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.IOS.name(),UmConfig.CasetType.unicast.name());
                Map<String,Object> map = new HashMap<>();
                map.put("title","您有一条新的报警信息");
                iosUm.setAlert(map);
//                iosUm.setNoAlert();
//                iosUm.setTitle("您有一条新的报警!");
                iosUm.setDeviceTokens(tokens.get("ios").toString());
            }
        }else if("area".equals(event)){
            // 点位变更 - 消息
            JSONObject json=new JSONObject();
            json.put("envent","area");
            andUm=(UmAndriodNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.Android.name(),UmConfig.CasetType.broadcast.name());
            andUm.setDisplayType(UmConfig.DisplayType.message.name());
            andUm.setCustomField(json.toString());
            iosUm=(UmIOSNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.IOS.name(),UmConfig.CasetType.broadcast.name());
            iosUm.setNoAlert();
            iosUm.setCustomField(json);
        }else if("alarmfinish".equals(event)){
            // 点位变更 - 消息
            JSONObject json=new JSONObject();
            json.put("envent","alarmfinish");
            andUm=(UmAndriodNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.Android.name(),UmConfig.CasetType.broadcast.name());
            andUm.setDisplayType(UmConfig.DisplayType.message.name());
            andUm.setCustomField(json.toString());
            iosUm=(UmIOSNotification) UmPushUtil.getUotificationBySys(UmConfig.Sys.IOS.name(),UmConfig.CasetType.broadcast.name());
            iosUm.setNoAlert();
            iosUm.setCustomField(json);
        }
        if(andUm!=null){
            com.alibaba.fastjson.JSONObject jsonObject = UmPushUtil.sendUmRequest(andUm);
            log.info("response" + jsonObject);
            // 如果是报警事件且发送推送失败,并且该报警级别为1.改为发送短信
            if("alarm".equals(event) && !jsonObject.getString("ret").equals("SUCCESS")){
                AlarmListInfoVo alarmListInfoVo =  alarmInfoService.getDetail(Integer.valueOf(params.get("id")));
                if(alarmListInfoVo.getAlarmLevel() == 1){
                    // 发送短信,通过token取userId
                    String[] tokens = andUm.getBody().get("device_tokens").toString().split(",");
                    for(String token : tokens){
                        UserEntity andUserEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("token",token));
                        ArrayList<String> parm = new ArrayList<>();
                        if(andUserEntity.getMobile() != null){
                            parm.add(DateUtils.format(alarmListInfoVo.getAlarmDate(),DateUtils.DATE_TIME_PATTERN).toString());
                            parm.add(alarmListInfoVo.getDefenceName());
                            parm.add(alarmListInfoVo.getAlarmType());
                            System.out.println(DateUtils.format(alarmListInfoVo.getAlarmDate(),DateUtils.DATE_TIME_PATTERN));
                            smsService.sendSms(andUserEntity.getMobile(), SmsConstant.templateId, parm);
                        }
                    }
                }
            }
        }
        if(iosUm!=null){
            com.alibaba.fastjson.JSONObject jsonObject = UmPushUtil.sendUmRequest(iosUm);
            log.info("response" + jsonObject);
            // 如果是报警事件且发送推送失败,并且该报警级别为1.改为发送短信
            if("alarm".equals(event) && !jsonObject.getString("ret").equals("SUCCESS")){
                AlarmListInfoVo alarmListInfoVo =  alarmInfoService.getDetail(Integer.valueOf(params.get("id")));
                if(alarmListInfoVo.getAlarmLevel() == 1){
                    // 发送短信,通过token取userId
                    String[] tokens = andUm.getBody().get("device_tokens").toString().split(",");
                    for(String token : tokens){
                        UserEntity iosUserEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("token",token));
                        ArrayList<String> parm = new ArrayList<>();
                        if(iosUserEntity.getMobile() != null){
                            parm.add(DateUtils.format(alarmListInfoVo.getAlarmDate(),DateUtils.DATE_TIME_PATTERN).toString());
                            parm.add(alarmListInfoVo.getDefenceName());
                            parm.add(alarmListInfoVo.getAlarmType());
                            System.out.println(DateUtils.format(alarmListInfoVo.getAlarmDate(),DateUtils.DATE_TIME_PATTERN));
                            smsService.sendSms(iosUserEntity.getMobile(), SmsConstant.templateId, parm);
                        }
                    }
                }
            }
        }
        return R.ok("接收成功");
    }



    /**
     * 模拟发送请求
     * @return
     */
    @PostMapping("/test")
    @ApiOperation("模拟联河光子发送请求")
    public R test(HttpServletRequest request) {
        // 创建默认的httpClient实例.
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("id", "1,2,3"));
        params.add(new BasicNameValuePair("envent", "alarm"));

        //params.add(new BasicNameValuePair("envent", "area"));

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://127.0.0.1:8080/hyopt/app/callback/info");
        CloseableHttpResponse response = null;
        try {
            // 加浏览器头防止被过滤
            post.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT5.1; en-US; rv:0.9.4)");
            post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            response = httpclient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                if (null != httpEntity) {
                    String retSrc = EntityUtils.toString(httpEntity);
                    System.out.println(retSrc);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.ok().put("data",response.getStatusLine().getStatusCode());
    }


}
